package com.jihox.abookpro;


import java.io.File;
import java.text.DecimalFormat;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLayoutChangeListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jihox.abookpro.R;
import com.jihox.abookpro.dao.OrderDAO;
import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.DeliveryInfo;
import com.jihox.abookpro.domain.Order;
import com.jihox.abookpro.domain.OrderListItem;
import com.jihox.abookpro.domain.OrderStatus;
import com.jihox.abookpro.domain.Page;
import com.jihox.abookpro.domain.PagePicture;
import com.jihox.abookpro.domain.OrderListItem.OrderItem;
import com.jihox.abookpro.fragment.OrderFragment;
import com.jihox.abookpro.uploader.OnProgressListener;
import com.jihox.abookpro.uploader.UploadService;
import com.jihox.abookpro.util.AndroidImageFile;
import com.jihox.abookpro.view.JHProgressDialog;

public class AccountDetailActivity extends BaseActivity {
	private RelativeLayout operationLayout;
	private RelativeLayout viewLogisticLayout;
	private TextView shareView;
	
	private OrderListItem order;
	private Order localOrder;
	private ImageView ivCover;
	private Bitmap bmCover;
	
	private ProgressBar progressBar;
	private UploadService uploadService;
	private JHProgressDialog pd;
	
	public static final String  EXPRESS_API_HOST="http://m.kuaidi100.com/query";
	private Handler expressHanlder;
	
//	// 下载对话框
//	private Dialog downloadDialog;
//	// 进度条
//	private ProgressBar mProgress;
//	// 显示下载数值
//	private TextView mProgressText;
//	// 终止标记
//	private boolean interceptFlag;
//	private HttpHandler httpHandler;
//
//	private ProgressDialog progress;
//	private BookProject bookproject;
//	private String templatePath;
//	private String resolvepath;
//	private String templateName;
	
//	private Handler handler = new Handler(){
//
//		@Override
//		public void handleMessage(Message msg) {
//			switch(msg.what){
//			case 1:	//修改其中的图片路径,并将数据写到数据库中去，然后去预览照片书	
//				Vector<Page> pages = bookproject.getBook().getPages();
//				for(int i=0;i<pages.size();i++){
//					List<PagePicture> pictures = pages.get(i).getPictures();
//					if(pictures.size()>0){
//						for(int j=0;j<pictures.size();j++){
//							String picPath = pictures.get(j).getImage().getPath();
//							if(pictures.get(j).isClipart()){
//								Log.i("msg_clipname", templatePath+"/"+picPath);
//								picPath = templatePath+"/"+picPath;
//							}else{
//								Log.i("msg_picname", resolvepath+picPath);
//								picPath = resolvepath+picPath;
//							}
//							 pictures.get(j).getImage().setPath(picPath);
//						}
//						pages.get(i).setPictures(pictures);
//					}else{
//						continue;
//					}
//				}
//				progress.dismiss();
//				Toast.makeText(AccountDetailActivity.this, "安装成功", Toast.LENGTH_SHORT).show();
//				Intent intent = new Intent();
//				intent.setClass(AccountDetailActivity.this, CurlActivity.class);  
//				Bundle mBundle = new Bundle();  
//				mBundle.putString("From", AccountDetailActivity.class.getName());
//				
////				if(OrderStatus.PRODUCTING.getStatus().equals(order.getStatus())){
////					mBundle.putString("worksn", order.getOrderId()+"-001");
////				}
////				if (OrderFragment.ordersListAdapter != null) {
////					OrderFragment.ordersListAdapter.clearCache();
////					System.gc();
////				}
//				MyApplication application = MyApplication.getInstance();
//				application.setBookProject(bookproject);
//				intent.putExtras(mBundle);  
//				AccountDetailActivity.this.startActivity(intent); 
//				break;
//			case 2://下载模板
//				String url = "http://192.168.0.244:8080/PBMFS2/show/download/"+templateName+".zip";
//				downloadTemplate(url, templatePath, templateName, null, true);
//				break;
//			}
//		}	
//		
//	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_account_detail);
		order = (OrderListItem)getIntent().getSerializableExtra("orderDetail");
		operationLayout = (RelativeLayout) findViewById(R.id.order_operation_layout);
		viewLogisticLayout = (RelativeLayout) findViewById(R.id.order_logistic_layout);
		shareView = (TextView) findViewById(R.id.order_share);
		ivCover = (ImageView) findViewById(R.id.order_ivcover);
		progressBar = (ProgressBar) findViewById(R.id.order_upload_progressbar);
		expressHanlder = getHandler();
//		OrderDAO orderHelper = new OrderDAO(AccountDetailActivity.this);
//		localOrder = orderHelper.getOrderInfo(order.getOrderId());
//		initView();
//		initHeader();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		OrderDAO orderHelper = new OrderDAO(AccountDetailActivity.this);
		localOrder = orderHelper.getOrderInfo(order.getOrderId());
		initView();
		initHeader();
		new Thread(){
			@Override
			public void run() {
				if (order.getOrderItems() != null
						&& order.getOrderItems().size() > 0) {
					if (localOrder!=null){
						bmCover = localOrder.getThumbnail();
					}
					
					Message msg = new Message();
					msg.what = 1;
					updateCoverHandler.sendMessage(msg);
				}
			}
		}.start();
		
		Intent sIntent = new Intent();
		ComponentName cn = new ComponentName(this, "com.jihox.abookpro.uploader.UploadService");  
		sIntent.setComponent(cn); 
		
		startService(sIntent);
		bindService(sIntent, conn, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	public void onPause(){
		super.onPause();
		if (uploadService!=null){
			uploadService.setOnProgressListener(null);
			this.unbindService(conn);
		}
	}
	
	ServiceConnection conn = new ServiceConnection() {  
        @Override  
        public void onServiceDisconnected(ComponentName name) {  
        }  
          
        @Override  
        public void onServiceConnected(ComponentName name, IBinder service) {  
            //返回一个MsgService对象  
        	uploadService = ((UploadService.UploadBinder)service).getService();  
            //注册回调接口来接收下载进度的变化  
        	uploadService.setOnProgressListener(new OnProgressListener() {  
        		
				@Override
				public void onProgress(String orderId, int status,
						int progress, List<String> waitingOrders) {
					if(OrderFragment.ordersListAdapter != null)
						OrderFragment.ordersListAdapter.updateProgressBar(orderId, progress, status, waitingOrders);
					
					//更新当前进度条
					if(order.getOrderId().equals(orderId)){
						progressBar.setProgress(progress);
						initOperationButton(R.drawable.upload_nocolor_flag, R.string.T_Order_Status_Uploading);
						operationLayout.setEnabled(false);
						if(status == Order.ORDER_STATUS_UPLOADED){
							progressBar.setProgress(100);
							progressBar.setProgress(0);
							TextView orderStatus = (TextView) findViewById(R.id.order_status);
							orderStatus.setText(OrderStatus.PRODUCTING.getStatus());
							order.setStatus(localOrder.getOrderStatusText());
							//弹出提示框
							showToast(getResources().getString(R.string.T_Upload_Success));
							initOperationButton(-1 , R.string.X_Buy_Again);
							operationLayout.setEnabled(true);
						}else if ( Order.ORDER_STATUS_UPLOAD_FAILED == status){
							progressBar.setProgress(0);
							TextView orderStatus = (TextView) findViewById(R.id.order_status);
							orderStatus.setText(R.string.T_Order_Status_Upload_Failed);
							order.setStatus(localOrder.getOrderStatusText());
							//弹出提示框
							showToast(getResources().getString(R.string.T_Order_Status_Upload_Failed));
							initOperationButton(-1 , R.string.X_Upload_Again);
							operationLayout.setEnabled(true);
						}
					}
				}
            });  
              
        }  
    }; 
    
	/**
	 * msg.what = 1: 加载成功 
	 */
	private Handler updateCoverHandler = new Handler(){
		@Override 
		public void handleMessage(Message msg){
			refreashView();
			switch(msg.what)
			{
				case 1:
					ivCover.setImageBitmap(bmCover);
					break;
				default:
					break;
			}
		}
	};
	
	//init头部
	private void initHeader(){
		Button backBtn = (Button) findViewById(R.id.ivBack);
		backBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				AccountDetailActivity.this.finish();
			}
		});
		TextView center = (TextView) findViewById(R.id.tvTitle);
		center.setText(R.string.X_Order_Detail);
		
		Button btnPreview = (Button) findViewById(R.id.head_btnOperation);
		if (this.localOrder == null){
			btnPreview.setVisibility(View.GONE);
		}else{
		//如果订单状态为生产中或者已发货，则用户可以进行产品预览
//		if( OrderStatus.PRODUCTING.getStatus().equals(order.getStatus()) || OrderStatus.DELIVERY.getStatus().equals(order.getStatus()) ){
			btnPreview.setText(R.string.Preview);
			btnPreview.setVisibility(View.VISIBLE);
			btnPreview.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
//					if (localOrder != null){//如果本地能查询到该订单信息则可以直接进行预览
						Intent intent = new Intent();
						intent.setClass(view.getContext(), CurlActivity.class);  
						Bundle mBundle = new Bundle();  
						mBundle.putString("From", AccountDetailActivity.class.getName());
						
						if(OrderStatus.PRODUCTING.getStatus().equals(order.getStatus())){
							mBundle.putString("worksn", order.getOrderId()+"-001");
						}
						if (OrderFragment.ordersListAdapter != null) {
							OrderFragment.ordersListAdapter.clearCache();
							System.gc();
						}
						MyApplication application = MyApplication.getInstance();
						application.setBookProject(localOrder.getBookProject());
						intent.putExtras(mBundle);  
						view.getContext().startActivity(intent); 
//					}else{//否则提示用户需要下载订单资源
//						showDialog();
//					}
				}
			 });
		}
//			}else{//否则不能进行预览
//				btnPreview.setVisibility(View.GONE);
//			}

	}
	
	//控制下方带图标的按钮  -1 表示不设置
	private void initOperationButton(int imageRes, int textRes)
	{
		ImageView images = (ImageView) findViewById(R.id.order_operation_image);
		TextView text = (TextView) findViewById(R.id.order_operation_text);
		
		//显示图象
		if(imageRes > 0)
		{
			images.setImageResource(imageRes);
		}else {
			images.setVisibility(View.GONE);
		}
		
		//显示文字
		if(textRes > 0 )
		{
			text.setText(textRes);
		}
		else {
			text.setText(" ");
		}
	}
	
	//初始化界面
	private void refreashView(){
		if(localOrder != null){
			if (localOrder.getOrderStatusText()!=null){
				TextView status = (TextView) findViewById(R.id.order_status);
				status.setText(localOrder.getOrderStatusText());
				order.setStatus(localOrder.getOrderStatusText());
			}
			
			operationLayout.setOnClickListener(operationListener);
			if(OrderStatus.NOTPAY.getStatus().equals(order.getStatus())){
				initOperationButton(-1 , R.string.T_Order_Status_Pay);
				operationLayout.setEnabled(true);
			}else if(OrderStatus.NOTUPLOAD.getStatus().equals(order.getStatus())){
				if (!order.isInUpload()) {
					progressBar.setProgress(0);
					initOperationButton(R.drawable.upload_nocolor_flag, R.string.Upload_Again);
					operationLayout.setEnabled(true);
				} else {
					initOperationButton(R.drawable.upload_nocolor_flag, R.string.T_Order_Status_Upload_Wait);
					operationLayout.setEnabled(false);
				}
			}else {
				progressBar.setProgress(100);
				progressBar.setProgress(0);
				initOperationButton(-1 , R.string.X_Buy_Again);
				operationLayout.setEnabled(true);
			}
		}
	}

	//初始化界面
	private void initView(){
		if(order != null){
			TextView orderNumber = (TextView) findViewById(R.id.order_detail_tvnumber);
			orderNumber.setText(order.getOrderId());
			TextView productName = (TextView) findViewById(R.id.order_detail_name);
			productName.setText(order.getOrderItems().get(0).getProductName());
			
			TextView orderRemark=(TextView) findViewById(R.id.order_remark_show);
			orderRemark.setText(order.getRemark());
			
			TextView receiver = (TextView) findViewById(R.id.order_receiver);
			receiver.setText(order.getReceiver());
			final TextView address1 = (TextView) findViewById(R.id.order_address1);
			final TextView address2 = (TextView) findViewById(R.id.order_address2);
			address1.setText(order.getAddress());
			
			address1.addOnLayoutChangeListener(new OnLayoutChangeListener() {
			    @Override
			    public void onLayoutChange(View v, int left, int top, int right,
			            int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
			        if (address1.getLineCount() > 1) {
			            int start = address1.getLayout().getLineStart(1);
			            String twoText = address1.getText().toString().substring(start);
			            address2.setText(twoText);
			            address2.setVisibility(View.VISIBLE);
			            address1.setMaxLines(1);
			        }
			    }
			});
			
			TextView phone = (TextView) findViewById(R.id.order_phone);
			phone.setText(order.getPhone());
			
			DecimalFormat df=new DecimalFormat("0.00");
			TextView status = (TextView) findViewById(R.id.order_status);
			status.setText(order.getStatus());
			TextView priceTotal = (TextView) findViewById(R.id.order_price_total);
			priceTotal.setText(df.format(order.getTotalAmount()));
			float payPrice = order.getTotalAmount() - order.getDiscountAmount();
			payPrice = payPrice < 0 ? 0 : payPrice;
			TextView tvPayPrice = (TextView) findViewById(R.id.order_pay_price);
			tvPayPrice.setText(df.format(payPrice));
			
			if (localOrder ==null){
				operationLayout.setVisibility(View.GONE);
			}else{
				operationLayout.setOnClickListener(operationListener);
				if(OrderStatus.NOTPAY.getStatus().equals(order.getStatus())){
					initOperationButton(-1 , R.string.T_Order_Status_Pay);
					operationLayout.setEnabled(true);
				}else if(OrderStatus.NOTUPLOAD.getStatus().equals(order.getStatus())){
					if (!order.isInUpload()) {
						initOperationButton(R.drawable.upload_nocolor_flag, R.string.Upload_Again);
						operationLayout.setEnabled(true);
					} else {
						initOperationButton(R.drawable.upload_nocolor_flag, R.string.T_Order_Status_Upload_Wait);
						operationLayout.setEnabled(false);
					}
				}else {
					initOperationButton(-1 , R.string.X_Buy_Again);
					operationLayout.setEnabled(true);
				}
			}
			
			
			if (order.getLogisticvos()!=null && order.getLogisticvos().size()>0){
				viewLogisticLayout.setVisibility(View.VISIBLE);
			}
			viewLogisticLayout.setOnClickListener(logisticListener);
			//生产中和已发货的订单可以分享
			if (localOrder!=null && order.getStatus().equals(OrderStatus.PRODUCTING.getStatus()) || order.getStatus().equals(OrderStatus.DELIVERY.getStatus())) {
				shareView.setVisibility(View.VISIBLE);
				shareView.setOnClickListener(shareClickListener);
			}
			
			if(order.getOrderItems() != null && order.getOrderItems().size() >0){
				OrderItem item = order.getOrderItems().get(0);
				TextView itemPrice = (TextView) findViewById(R.id.order_price);
				itemPrice.setText(df.format(item.getPrice()) + "元/本");
				TextView itemNumber = (TextView) findViewById(R.id.order_total_number);
				itemNumber.setText(item.getNumber() + "本");
				TextView discountCode = (TextView) findViewById(R.id.order_discount_code);
				discountCode.setText(order.getDiscountCode());
				TextView discountPrice = (TextView) findViewById(R.id.order_discount_price);
				float discountAmount = order.getDiscountAmount();
				if (item.getPrice()*item.getNumber()<discountAmount){
					discountAmount = item.getPrice()*item.getNumber();
				}
				discountPrice.setText(df.format(discountAmount) + "元");
			}
		}
	};
	private OnClickListener operationListener = new OnClickListener(){

		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			TextView tvStatus = (TextView) view.findViewById(R.id.order_operation_text);
			if(tvStatus.getText().equals(view.getContext().getString(R.string.T_Order_Status_Pay))){
				//前往付款 
				BookProject bookProject = localOrder.getBookProject();
				if(((MyApplication)view.getContext().getApplicationContext()).checkImageExist(bookProject) != null){
					AccountDetailActivity.showLostDialog(view, bookProject,localOrder);
				}else {
					AccountDetailActivity.goToPayActivity(view, localOrder, order);
				}
				return;
				
			}else if(tvStatus.getText().equals(view.getContext().getString(R.string.Upload_Again))){
				//继续上传 
				localOrder.setThumbnail(null);
				uploadFile( localOrder);
				if(OrderFragment.ordersListAdapter.getData() != null)
				for(OrderListItem item : OrderFragment.ordersListAdapter.getData()){
					if(item.getOrderId().equals(order.getOrderId())){
						item.setInUpload(true);
						order.setInUpload(true);
						break;
					}
				}
				initOperationButton(R.drawable.upload_nocolor_flag, R.string.T_Order_Status_Upload_Wait);
				operationLayout.setEnabled(false);
				return;
				
			}else if(tvStatus.getText().equals(view.getContext().getString(R.string.T_Order_Status_Upload_Wait))){
				//等待上传
				return ;
				
			}else if(tvStatus.getText().equals(view.getContext().getString(R.string.T_Order_Status_Uploading))){
				//正在上传
				return ;
				
			}else if((tvStatus.getText().equals(view.getContext().getString(R.string.X_Buy_Again)))){
				//再次购买
				BookProject bookProject = localOrder.getBookProject();
				if(((MyApplication)view.getContext().getApplicationContext()).checkImageExist(bookProject) != null){
					AccountDetailActivity.showLostDialog(view, bookProject,localOrder);
				}else {
					//跳转到订单页面
					goToOrderActivity(AccountDetailActivity.this,localOrder);
				}
				return ;
			}
		}
	};
	
	private OnClickListener logisticListener = new OnClickListener(){
		@Override
		public void onClick(View view) {
			pd = JHProgressDialog.show(AccountDetailActivity.this, null,
					getResources().getString(R.string.T_Loading));
			new Thread(getExpressInfoRunnable).start();

		}
	};
	
	private OnClickListener shareClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			
			Log.d("share", "share to friends");
			MyApplication application = MyApplication.getInstance();
			application.setWorksn(localOrder.getWorksn());
			application.setBookProject(localOrder.getBookProject());
			Intent intent=new Intent(AccountDetailActivity.this,ShareActivity.class);
			startActivity(intent);
			finish();
		}
	};
	
	private Runnable getExpressInfoRunnable = new Runnable() {
		@Override
		public void run() {
			StringBuffer sb=new StringBuffer();
			HttpClient httpclient = new DefaultHttpClient();
			sb.append(EXPRESS_API_HOST).append("?id=1").append("&type=").
			append(order.getLogisticvos().get(0).getShippingTypeVo().getCode()).
			append("&postid=").append(order.getLogisticvos().get(0).getCode());
			String url=sb.toString();
			
			HttpGet httpGet = new HttpGet(url);

			
			try {
				HttpResponse httpResponse = httpclient.execute(httpGet);
				String result = EntityUtils.toString(httpResponse.getEntity());
				Message msg=new Message();
				msg.what=0;
				msg.obj=result;
				expressHanlder.sendMessage(msg);
			} catch (Exception e) {
				expressHanlder.sendEmptyMessage(-1);
				e.printStackTrace();
			} finally {
				httpclient.getConnectionManager().shutdown();
			}
		}
	};
	
	//初始化消息处理器
	private Handler getHandler(){
		return new Handler(){
		@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				pd.dismiss();
				if(msg.what==0){

					Intent it=new Intent(AccountDetailActivity.this, OrderLogistic.class);
					it.putExtra("jsonStr", msg.obj.toString());
					startActivity(it);
					//overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
				}
				if(msg.what==-1){
					showToast(getResources().getString(R.string.T_NoNet));
				}
			}	
		};
	}
	
	public static void goToEditActivity(View view, BookProject bookProject, Order localOrder){
		ShowImageActivity.selectedPhotoList.clear();
		for(Page currentPage : bookProject.getBook().getPages()){
			if(currentPage.getPictures() != null && currentPage.getPictures().size() > 0){
				for(PagePicture pagePicture : currentPage.getPictures()){
					if(!pagePicture.isClipart()){
						String path = pagePicture.getImage().getPath();
						File file = new File(path);
						AndroidImageFile selectedFile = new AndroidImageFile();
						selectedFile.setPath(path);
						selectedFile.setFolderName(file.getParent());
						ShowImageActivity.selectedPhotoList.add(selectedFile);
					}
				}
			}
		}
		
		ShowImageActivity.showNextButton = false;
		Intent intent = new Intent();    
		intent.putExtra("templateName", localOrder.getTemplateName());
		intent.putExtra("bookProduct", bookProject.getBook().getProduct());
		intent.setClass(view.getContext(), GallerySelectActivity.class);
		Bundle mBundle = new Bundle();  
		if(bookProject.getBook().getPages().get(0).getCaptions()!=null&&bookProject.getBook().getPages().get(0).getCaptions().size()>0)
			mBundle.putString("Caption", bookProject.getBook().getPages().get(0).getCaptions().get(0).getText()); 
		mBundle.putString("From", AccountDetailActivity.class.getName());
		intent.putExtras(mBundle);
		view.getContext().startActivity(intent);
	}
	
	public static void goToPayActivity(View view, Order localOrder, OrderListItem orderItem){
		Intent intent = new Intent();
		intent.setClass(view.getContext(), PayActivity.class);
		Bundle bundle = new Bundle();
		localOrder.setThumbnail(null);
		localOrder.setPrice(orderItem.getOrderItems().get(0).getPrice());
		localOrder.setNumber(String.valueOf(orderItem.getOrderItems().get(0).getNumber()));
		localOrder.setProductId(String.valueOf(orderItem.getOrderItems().get(0).getProductId()));
		localOrder.setCreatedtime(String.valueOf(orderItem.getCreateDate().getTime()));
		localOrder.setShippingfee(orderItem.getTotalAmount()-orderItem.getOrderItems().get(0).getPrice()*orderItem.getOrderItems().get(0).getNumber());
		DeliveryInfo delivery = new DeliveryInfo();
		delivery.setConsignee(orderItem.getReceiver());
		delivery.setAddress(orderItem.getAddress());
		delivery.setMobile(orderItem.getPhone());
		localOrder.setDeliveryInfo(delivery);
		MyApplication application = MyApplication.getInstance();
		application.setBookProject(localOrder.getBookProject());
		application.setWorksn(localOrder.getWorksn());
		
		bundle.putSerializable("OrderInfo", localOrder);
		bundle.putString("From", AccountDetailActivity.class.getName());
		intent.putExtras(bundle);
		view.getContext().startActivity(intent);
	}
	
	public static void goToOrderActivity(Context context, Order localOrder){
		Intent intent = new Intent();
		intent.setClass(context, OrderActivity.class);  
		intent.putExtra("templateName", localOrder.getTemplateName());
		
		Bundle mBundle = new Bundle();  
		MyApplication application = MyApplication.getInstance();
		application.setBookProject(localOrder.getBookProject());
		Bitmap coverBitmap = null;
		if (localOrder.getThumbnail()==null){
			OrderDAO dao = new OrderDAO(context);
			coverBitmap = dao.getOrderThumbnail(localOrder.getOrderId());
		}else{
			coverBitmap = localOrder.getThumbnail().copy(Config.ARGB_4444, false);
		}
		
		mBundle.putString("From", AccountDetailActivity.class.getName());
		mBundle.putString("coverBitmap", CurlActivity.saveCoverBitmap(context, coverBitmap, 10,"cover.png"));
		mBundle.putString("OldWorksn", localOrder.getWorksn());

		intent.putExtras(mBundle);  
		context.startActivity(intent);
	}
	public static void showLostDialog(final View view, final BookProject bookProject,final Order localOrder) {
		final Dialog dialog = new Dialog(view.getContext(), R.style.JHDialog);
		//设置它的ContentView
		dialog.setContentView(R.layout.dialog_general);
		Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
		Button buttonCancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);
		TextView dialogTitle = (TextView) dialog.findViewById(R.id.dialog_title);
		TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialog_message);

		buttonOK.setBackgroundResource(R.drawable.delete_style);
		buttonCancel.setBackgroundResource(R.drawable.grey_style);
		buttonOK.setText(R.string.T_Ok);
		buttonCancel.setText(R.string.T_Cancel);
		dialogTitle.setText(R.string.T_Photo_Remind);
		dialogMessage.setText(R.string.T_Photo_Lost);

		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				goToEditActivity(view, bookProject, localOrder);
			}
		});
		buttonCancel.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				dialog.dismiss();
			}
		});
		dialog.show();
	}
	
	/**
	 * 上传文件
	 */
	private void uploadFile(Order orderInfo){
		uploadService.addUploadTask(orderInfo);
	}
	
//	//提示下载dialog
//	private void showDialog() {
//
//		final Dialog dialog = new Dialog(AccountDetailActivity.this,
//				R.style.JHDialog);
//		// 设置它的ContentView
//		dialog.setContentView(R.layout.dialog_general);
//		Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
//		Button buttonCancel = (Button) dialog
//				.findViewById(R.id.dialog_button_cancel);
//		TextView dialogTitle = (TextView) dialog
//				.findViewById(R.id.dialog_title);
//		TextView dialogMessage = (TextView) dialog
//				.findViewById(R.id.dialog_message);
//
//		buttonOK.setBackgroundResource(R.drawable.delete_style);
//		buttonCancel.setBackgroundResource(R.drawable.grey_style);
//		buttonOK.setText(R.string.T_Down_Load);
//		buttonCancel.setText(R.string.T_Cancel);
//
//		dialogTitle.setText(R.string.T_PreView_Hint);
//		dialogMessage.setText(R.string.T_PreView_Hint_Text);
//
//		buttonOK.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				String dlname = order.getOrderId()+"_"+order.getOrderId()+"-001";
//				String url = ConfigProperties.getOrderResourcesDown()+dlname+".zip";
//				final String path = Environment.getExternalStorageDirectory()+ ConfigProperties.getOrderResourcesPath() + order.getOrderId();
//				downloadTemplate(url,path,order.getOrderId()+"-001","正在下载订单资源",false);
//				dialog.dismiss();
//				
//			}
//		});
//		buttonCancel.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				dialog.dismiss();
//			}
//		});
//
//		dialog.show();
//	}
	
//	/**
//	 * 下载模板
//	 */
//	private void downloadTemplate(String url,final String dlpath,final String dlname,final String titlename,final boolean istemplate){
//		HttpUtils http = new HttpUtils();
//		Log.i("msg", url+"--------------------"+dlpath);
//		httpHandler = http.download(url,dlpath+"/"+dlname+".zip",new RequestCallBack<File>() {
//
//			@Override
//			public void onFailure(HttpException arg0, String arg1) {
//				// TODO Auto-generated method stub
//				
//				Log.i("msg", "--------------------fail"+arg0+arg1);
//			}
//
//			@Override
//			public void onLoading(long total, long current,
//					boolean isUploading) {
//				 //textView.setText("下载进度："+current+"/"+count);
//				
//				Log.i("msg", "--------------------"+total+"----------"+current);
//				int progress = (int) (((double)current / total) * 100);
//				Log.i("msg", "--------------------"+progress);
//				if(!istemplate){
//					mProgress.setProgress(progress);
//					
//					mProgressText.setText(current/1024+"kb" + "/" + total/1024+"kb");
//				}
//				
//			}
//
//			@Override
//			public void onStart() {
//				if(!istemplate){
//					showDownloadDialog(titlename);
//				}
//			}
//
//			@Override
//			public void onSuccess(ResponseInfo<File> arg0) {
//				// TODO Auto-generated method stub
////				Toast.makeText(MainActivity.this, "模板下载成功", Toast.LENGTH_SHORT).show();
//				if(!istemplate){
//					progress = new ProgressDialog(AccountDetailActivity.this);
//					progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//					progress.setMessage("正在安装，请稍后...");
//					progress.show();
//					Log.i("msg", "--------------------success");
//					downloadDialog.dismiss();
//				}
//				httpHandler.cancel();
//				try {		
//					upZipFile(dlpath+"/"+dlname+".zip", dlpath,istemplate);
//				} catch (IOException e) {
//					e.printStackTrace();
//					Toast.makeText(AccountDetailActivity.this, "安装失败", Toast.LENGTH_SHORT).show();
//				}
//			}
//			
//		});
//	}
//	
//	
//	/**
//	 * 显示下载对话框
//	 */
//	private void showDownloadDialog(String title) {
//
//		downloadDialog = new Dialog(this, R.style.JHDialog);
//		// 设置它的ContentView
//		downloadDialog.setContentView(R.layout.dialog_download);
//		Button buttonCancel = (Button) downloadDialog
//				.findViewById(R.id.dialog_button_cancel);
//		mProgress = (ProgressBar) downloadDialog
//				.findViewById(R.id.update_progress);
//		mProgressText = (TextView) downloadDialog
//				.findViewById(R.id.update_progress_text);
//		TextView dialogTitle = (TextView) downloadDialog
//				.findViewById(R.id.dialog_title);
//		buttonCancel.setBackgroundResource(R.drawable.grey_style);
//		buttonCancel.setText("取消");
//		dialogTitle.setText(title);
//
//		buttonCancel.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//				downloadDialog.dismiss();
//				interceptFlag = true;
//				httpHandler.cancel();
//			}
//			
//		});
//
//		downloadDialog.setOnKeyListener(new OnKeyListener() {
//			@Override
//			public boolean onKey(DialogInterface arg0, int keyCode,
//					KeyEvent event) {
//				if (keyCode == KeyEvent.KEYCODE_BACK) {
//					downloadDialog.dismiss();
//					interceptFlag = true;
//					httpHandler.cancel();
//					return true;
//				}
//				return false;
//			}
//		});
//
//		downloadDialog.setCanceledOnTouchOutside(false);
//		downloadDialog.show();
//	}
//	
//	/**
//	 * 解压zip
//	 * @throws IOException 
//	 */
//	private void upZipFile(String archive,String decompressDir,boolean istemp) throws IOException{
//		BufferedInputStream bi;
//		ZipFile zf = new ZipFile(archive, "GBK");
//		Enumeration e = zf.getEntries();
//		String xmlname = null;//订单资源中xml文件的名称
//		while(e.hasMoreElements()){
//			ZipEntry ze2 = (ZipEntry) e.nextElement();
//			String entryName = ze2.getName();
//			String path = decompressDir +"/"+entryName;
//			if(ze2.isDirectory()){//判断当前读取的是否是目录
//				Log.i("msg", "正在创建解压目录"+entryName);
//				File decompressDirFile = new File(path);
//				if(!decompressDirFile.exists()){
//					decompressDirFile.mkdirs();
//				}
//			}else{//解压出的是文件
////				Log.i("msg", "正在创建解压文件"+entryName);
//				String fileDir = path.substring(0, path.lastIndexOf("/"));
//				File fileDirFile = new File(fileDir);
//				if(!fileDirFile.exists()){
//					fileDirFile.mkdirs();
//				}
//				if(!istemp){
//					if(entryName.endsWith(".phb")){//如果文件后缀名为.phb则更换后缀名为.xml
//						String name = entryName.substring(0, entryName.lastIndexOf("."));
//	//					Log.i("msg",entryName+"------"+name);
//						xmlname = entryName = name+".xml";
//					}
//				}
////				Log.i("msg", "正在创建解压文件"+entryName+"-----"+entryName.endsWith(".phb"));
//				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(decompressDir+"/"+entryName));
//				bi = new BufferedInputStream(zf.getInputStream(ze2));			
//				byte[] readContent = new byte[1024];
//				int readCount = bi.read(readContent);
//				while(readCount!=-1){
//					bos.write(readContent,0, readCount);
//					readCount = bi.read(readContent);
//					
//				}
//				bos.close();
//				
//			}
//		}
//		zf.close();
//		//模板解压成功，删除下载的压缩文件包
//		File file = new File(archive); 
//		file.delete();
//		if(istemp){
//			Message msg = handler.obtainMessage();
//			msg.what = 1;
//			handler.sendMessageDelayed(msg, 1500);
//			return;
//		}
//		//解压完成后解析.xml文件
//		//下载的订单资源文件夹路径
//		resolvepath = Environment.getExternalStorageDirectory()+ ConfigProperties.getOrderResourcesPath() 
//				+ order.getOrderId()+"/";
//		BookProjectDAO bdao = new BookProjectDAO();
//		try {
//			bookproject = bdao.getBookProject(resolvepath+xmlname);
////			Log.i("msg_bok", bookproject.toString());
//			//模板名称
//			templateName = bookproject.getBook().getTemplateName();
//			Log.i("msg_templateName", templateName.toString());
//			//模板文件夹路径
//			templatePath = Environment.getExternalStorageDirectory()+ConfigProperties.getTemplatePath()+templateName;
//			//查询本地是否存在该模板，若不存在则下载该模板
//			File temfile = new File(templatePath);
//			if(!temfile.exists()){
//				Message msg = handler.obtainMessage();
//				msg.what = 2;
//				handler.sendMessage(msg);
//			}else{
//				Message msg = handler.obtainMessage();
//				msg.what = 1;
//				handler.sendMessageDelayed(msg, 1500);
//			}
//			
//		} catch (Exception e1) {
//			e1.printStackTrace();
//		}
//				
//	}
	
}
